package com.firesafe.common.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class FeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //获取原始请求
                ServletRequestAttributes attribute= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request=attribute.getRequest();
                //获取原始请求中的header
                String token=request.getHeader("token");
                //同步请求头，将原始请求的header信息同步到feign请求中
                requestTemplate.header("token",token);
            }
        };
    }
}
